package com.eqdd.yiqidian.ui.tongxunlu;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import com.eqdd.floatingmenu.MenuItem;
import com.eqdd.floatingmenu.TopRightMenu;
import com.eqdd.yiqidian.BumenListFragmentCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.recycleadapter.BaseMultiItemQuickAdapter;
import com.eqdd.yiqidian.adapter.recycleadapter.BaseViewHolder;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.recycleadapter.entity.MultiItemEntity;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.BaseFragment;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.SectionArcBean;
import com.eqdd.yiqidian.bean.rebuild.DepartmentListResultBean;
import com.eqdd.yiqidian.bean.rebuild.EmploymentListResultBean;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.ui.base.TapActivity;
import com.eqdd.yiqidian.ui.mine.UserCardActivity;
import com.eqdd.yiqidian.utils.ImageUtil;
import com.eqdd.yiqidian.utils.ListUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx2.adapter.FlowableBody;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.BiFunction;

/**
 * Created by lvzhihao on 17-5-23.
 */

public class TongshiListFragment extends BaseFragment {


    private BumenListFragmentCustom databinding;

    private DepartmentListResultBean departmentListResultBean;

    private TopRightMenu mTopRightMenu;
    private SlimAdapterEx slimAdapterEx;
    private DepartmentListResultBean departmentChoose;
    private ArrayList<Object> datas;
    private List<DepartmentListResultBean> departList;
    private List<EmploymentListResultBean> employList;

    @Override
    protected void setView() {
        if (slimAdapterEx == null) {
            databinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

            slimAdapterEx = SlimAdapterEx.create().register(R.layout.item_edit_title_type, new SlimInjector<String>() {
                @Override
                public void onInject(String data, IViewInjector injector) {
                    injector.text(R.id.tv_top_title, data);
                }
            }).register(R.layout.list_item_section, new SlimInjector<DepartmentListResultBean>() {
                @Override
                public void onInject(DepartmentListResultBean data, IViewInjector injector) {
                    injector.text(R.id.tv_name, data.getDepartName());
                }
            }).register(R.layout.list_item_10, new SlimInjector<EmploymentListResultBean>() {
                @Override
                public void onInject(EmploymentListResultBean data, IViewInjector injector) {
                    injector.text(R.id.tv_upper_left_content, data.getStaffName())
                            .text(R.id.tv_upper_right_content, data.getDepartName())
                            .text(R.id.tv_down_right_content, data.getPostName())
                            .with(R.id.iv_head, v -> {
                                ImageUtil.setCircleImage(data.getIphoto(), (ImageView) v);
                            })
                            .invisible(R.id.iv_enter);
                }
            })
                    .attachTo(databinding.recyclerView);
            ItemClickSupport.addTo(databinding.recyclerView).setOnItemClickListener((rv, p, v) -> {

                if (slimAdapterEx.getData().get(p) instanceof DepartmentListResultBean) {
                    departmentChoose = (DepartmentListResultBean) slimAdapterEx.getData().get(p);
                    ((TapActivity) getActivity()).addFragment(departmentChoose);
                } else if (slimAdapterEx.getData().get(p) instanceof EmploymentListResultBean) {
                    EmploymentListResultBean emBean = (EmploymentListResultBean) slimAdapterEx.getData().get(p);
                    Bundle bundle = new Bundle();
                    bundle.putString(Config.GUID, emBean.getGuid());
                    startActivity(UserCardActivity.class, bundle);
                }
            })
                    .setOnItemLongClickListener((rv, p, v) -> {
                        if (slimAdapterEx.getData().get(p) instanceof EmploymentListResultBean) {
                            if (mTopRightMenu == null) {
                                mTopRightMenu = new TopRightMenu(getActivity());
                                List<MenuItem> menuItems = new ArrayList<>();
                                menuItems.add(new MenuItem("发送消息"));
                                menuItems.add(new MenuItem("拨打电话"));
                                menuItems.add(new MenuItem("设置标签"));
                                mTopRightMenu
                                        .setHeight(320)     //默认高度480
                                        .setWidth(280)      //默认宽度wrap_content
                                        .showIcon(false)     //显示菜单图标，默认为true
                                        .dimBackground(false)        //背景变暗，默认为true
                                        .needAnimationStyle(true)   //显示动画，默认为true
                                        .setAnimationStyle(R.style.TRM_ANIM_STYLE)
                                        .addMenuList(menuItems)
                                        .setOnMenuItemClickListener((position) -> {
                                            System.out.println(position);
                                        });
                            }
                            mTopRightMenu.showAsDropDown(v, 200, -80);    //带偏移量
                        }
                        return false;
                    });
        }
        refresh();
    }

    public void refresh() {
        ((BaseActivity) getActivity()).showLoading();
        Flowable<String> departFlow = OkGo.<String>post(HttpConfig.BASE_URL + HttpConfig.Select_SECTION)
                .params("ParentId", departmentListResultBean.getDepartId())
                .params("CompanyId", departmentListResultBean.getCompanyId())
                .converter(new StringConvert())
                .adapt(new FlowableBody<String>());
        Flowable<String> employmentFlow = OkGo.<String>post(HttpConfig.BASE_URL + HttpConfig.SELECT_EMPLOYMENT)
                .params("departId", departmentListResultBean.getDepartId())
                .params("companyId", departmentListResultBean.getCompanyId())
                .converter(new StringConvert())
                .adapt(new FlowableBody<String>());
        Flowable.combineLatest(departFlow, employmentFlow, new BiFunction<String, String, Object>() {
            @Override
            public Object apply(@NonNull String s, @NonNull String s2) throws Exception {

                HttpResult<List<DepartmentListResultBean>> httpResultDepartList = new Gson().fromJson(s, new TypeToken<HttpResult<List<DepartmentListResultBean>>>() {
                }.getType());
                if (httpResultDepartList.getStatus() == 200) {
                    departList = httpResultDepartList.getItems();
                }

                HttpResult<List<EmploymentListResultBean>> httpResultEmployList = new Gson().fromJson(s2, new TypeToken<HttpResult<List<EmploymentListResultBean>>>() {
                }.getType());
                if (httpResultEmployList.getStatus() == 200) {
                    employList = httpResultEmployList.getItems();
                }
                return "1";
            }
        })
                .subscribe((s) -> {
                    datas.clear();
                    if (!ListUtil.isEmpty(departList)) {
                        datas.add("部门");
                        datas.addAll(departList);
                    }
                    if (!ListUtil.isEmpty(employList)) {
                        datas.add("人员");
                        datas.addAll(employList);
                    }
                    slimAdapterEx.updateData(datas);
                }, e -> {
                    ToastUtil.showShort(Config.SERVER_ERROR);
                    System.out.println(e.toString());
                    ((BaseActivity) getActivity()).hideLoading();
                }, () -> {
                    ((BaseActivity) getActivity()).hideLoading();
                });
    }

    @Override
    protected void initData() {
        Bundle arguments = getArguments();
        departmentListResultBean = arguments.getParcelable(Config.DEPARTMENT);
        datas = new ArrayList<>();
    }

    @Override
    public ViewDataBinding initBinding(LayoutInflater inflater) {
        return databinding = DataBindingUtil.inflate(inflater, R.layout.fragment_bumen_list, null, false);
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}